package com.lanlian.commonlib.dao;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

import com.lanlian.commonlib.bean.RespUserLogin;
import com.lanlian.commonlib.bean.UserInfo;
import com.lanlian.commonlib.bean.db.DBMarketS;
import com.lanlian.commonlib.bean.db.DBMarketSerch;
import com.lanlian.commonlib.bean.db.DBMessage;
import com.lanlian.commonlib.bean.db.DBSearchQuestionHistory;
import com.lanlian.commonlib.bean.db.DBStyle;
import com.lanlian.commonlib.bean.db.DBUser;
import com.lanlian.commonlib.greendao.DBMessageDao;
import com.lanlian.commonlib.greendao.DBUserDao;
import com.lanlian.commonlib.greendao.DaoMaster;
import com.lanlian.commonlib.greendao.DaoSession;
import com.lanlian.utillib.PreferencesUtils;

import java.util.List;

public class DBManager {

    private static DBManager mDBManager;
    private Context mContext;

    private DBOpenHelper mOpenHelper;
    private DaoSession mDaoSession;

    private DBManager() {
    }

    public static DBManager getInstance() {
        if (mDBManager == null) {
            synchronized (DBManager.class) {
                if (mDBManager == null) {
                    mDBManager = new DBManager();
                }
            }
        }
        return mDBManager;
    }

    public void init(Context context) {
        this.mContext = context;
        mOpenHelper = new DBOpenHelper(context, "lanlian.db", null);
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(db);
        mDaoSession = daoMaster.newSession();
    }

    public void close() {
        mDaoSession = null;
        if (mOpenHelper != null) {
            mOpenHelper.close();
        }
    }

    /**
     * 是否第一次运行
     */
    public boolean isFirstRun() {
        return PreferencesUtils.getBoolean(mContext, "isFirstRun_v1.0.0", true);
    }

    public void setFirstRunned() {
        PreferencesUtils.putBoolean(mContext, "isFirstRun_v1.0.0", false);
    }

    /**
     * 跟单提示
     */
    public boolean isShowDocumentaryTips() {
        return PreferencesUtils.getBoolean(mContext, "isShowDocumentaryTips_v1.0.0", true);
    }

    public void setShowDocumentaryTips() {
        PreferencesUtils.putBoolean(mContext, "isShowDocumentaryTips_v1.0.0", false);
    }

    /**
     * 当前版本记录的APP最新版本号
     */
    public int getTempVersionCode() {
        return PreferencesUtils.getInt(mContext, "temp_version_code", 0);
    }

    public void setTempVersionCode(int temp_version_code) {
        PreferencesUtils.putInt(mContext, "temp_version_code", temp_version_code);
    }

    /**
     * 用户id
     */
    public long getUserId() {
        return PreferencesUtils.getLong(mContext, "user_id", 0);
    }

    public void setUserId(long userId) {
        PreferencesUtils.putLong(mContext, "user_id", userId);
    }


    /**
     * 是否是老用户 备注：1:老用户，2：已补充资料老用户，0：新用户
     */
    public int getIsOldUser() {
        return PreferencesUtils.getInt(mContext, "isOldUser");
    }

    public void setIsOldUser(int isOldUser) {
        PreferencesUtils.putInt(mContext, "isOldUser", isOldUser);
    }

    /**
     * 账户NO
     */
    public String getAccountNo() {
        return PreferencesUtils.getString(mContext, "accountNo");
    }

    public void setAccountNo(String accountNo) {
        PreferencesUtils.putString(mContext, "accountNo", accountNo);
    }

    /**
     * 手机号码 隐藏前七位 *******3333
     */
    public String getRechargeMobile() {
        return PreferencesUtils.getString(mContext, "rechargeMobile");
    }

    public void setRechargeMobile(String rechargeMobile) {
        PreferencesUtils.putString(mContext, "rechargeMobile", rechargeMobile);
    }

    /**
     * 用户token
     */
    public String getToken() {
        return PreferencesUtils.getString(mContext, "token", "");
    }

    public void setToken(String token) {
        PreferencesUtils.putString(mContext, "token", token);
    }

    /**
     * 交易二次确认，默认需要
     */
    public boolean getSecondConfirm() {
        return PreferencesUtils.getBoolean(mContext, "second_confirm", true);
    }

    public void setSecondConfirm(boolean secondConfirm) {
        PreferencesUtils.putBoolean(mContext, "second_confirm", secondConfirm);
    }

    /**
     * K线颜色 1.红涨绿跌 2.绿涨红跌
     */
    public int getKLineColor() {
        return PreferencesUtils.getInt(mContext, "kline_color", 1);
    }

    public void setKLineColor(int klineColor) {
        PreferencesUtils.putInt(mContext, "kline_color", klineColor);
    }

    /**
     * 主题色 1.正常 2.夜间
     */
    public int getTopicColor() {
        return PreferencesUtils.getInt(mContext, "topic_color", 1);
    }

    public void setTopicColor(int topicColor) {
        PreferencesUtils.putInt(mContext, "topic_color", topicColor);
    }

    /**
     * 是否已经登录
     */
    public boolean isLogined() {
        return getUserId() != 0 && !TextUtils.isEmpty(getToken());
    }

    /**
     * 本地登出
     */
    public void setLoginOut() {
        setUserId(0);
        setToken("");
    }

    /**
     * 设置User数据到本地数据库中
     */
    public boolean saveUser(RespUserLogin respLogin) {
        try {
            UserInfo userInfo = respLogin.getUserInfo();

            setUserId(userInfo.getId());
            setToken(respLogin.getToken());
            setRechargeMobile(userInfo.getChargeMobile());
            setIsOldUser(userInfo.getIsOldUser());
            setAccountNo(userInfo.getAccountNo());

            DBUserDao userDao = mDaoSession.getDBUserDao();
            DBUser user = userDao.load(getUserId());
            if (user != null) {
                user.setUser(respLogin);
                userDao.update(user);
            } else {
                user = new DBUser(respLogin);
                userDao.insert(user);
            }
            return true;
        } catch (Exception e) {
            e.fillInStackTrace();
        }
        return false;
    }

    public DBUser getUser() {
        try {
            DBUserDao userDao = mDaoSession.getDBUserDao();
            DBUser dbUser = userDao.load(getUserId());
            userDao.update(dbUser);
            return dbUser;
        } catch (NullPointerException ignored) {
            return null;
        }
    }

    public void updateUser(DBUser user) {
        DBUserDao userDao = mDaoSession.getDBUserDao();
        userDao.update(user);
    }
    public void deleteAllMarketSearch() {
        try {
            mDaoSession.getDBMarketSerchDao().deleteAll();
        } catch (Exception ignored) {
            ignored.printStackTrace();
        }
    }

    public List<DBStyle> getStyle(){
        try {
            return mDaoSession.getDBStyleDao().queryBuilder().list();
        } catch (Exception ignored) {
            ignored.printStackTrace();
            return null;
        }
    }
    public void setStyle(DBStyle style) {
        try {
            mDaoSession.getDBStyleDao().insertOrReplace(style);
        } catch (Exception ignored) {
            ignored.printStackTrace();
        }
    }
    public List<DBMarketS> getMarketS() {
        try {
            return mDaoSession.getDBMarketSDao().queryBuilder().list();
        } catch (Exception ignored) {
            ignored.printStackTrace();
            return null;
        }
    }
    public void setMarketS(DBMarketS search) {
        try {
            mDaoSession.getDBMarketSDao().insertOrReplace(search);
        } catch (Exception ignored) {
            ignored.printStackTrace();
        }
    }
    public void deleteMarketS(String id) {
        try {
            mDaoSession.getDBMarketSDao().deleteByKey(id);
        } catch (Exception ignored) {
            ignored.printStackTrace();
        }
    }
    public List<DBMarketSerch> getMarketSearch() {
        try {
            return mDaoSession.getDBMarketSerchDao().queryBuilder().list();
        } catch (Exception ignored) {
            ignored.printStackTrace();
            return null;
        }
    }

    public void setMarketSearch(DBMarketSerch search) {
        try {
            mDaoSession.getDBMarketSerchDao().insertOrReplace(search);
        } catch (Exception ignored) {
            ignored.printStackTrace();
        }
    }
    public void deleteMarketSearch(String id) {
        try {
            mDaoSession.getDBMarketSerchDao().deleteByKey(id);
        } catch (Exception ignored) {
            ignored.printStackTrace();
        }
    }


    public List<DBSearchQuestionHistory> getSearchQuestionHistory() {
        try {
            return mDaoSession.getDBSearchQuestionHistoryDao().queryBuilder().limit(5).list();
        } catch (Exception ignored) {
            return null;
        }
    }

    public void setSearchQuestionHistory(DBSearchQuestionHistory searchQuestionHistory) {
        try {
            mDaoSession.getDBSearchQuestionHistoryDao().insertOrReplace(searchQuestionHistory);
        } catch (Exception ignored) {
        }
    }

    public void deleteSearchQuestionHistory(int id) {
        try {
            mDaoSession.getDBSearchQuestionHistoryDao().deleteByKey(id);
        } catch (Exception ignored) {
        }
    }

    public void deleteAllSearchQuestionHistory() {
        try {
            mDaoSession.getDBSearchQuestionHistoryDao().deleteAll();
        } catch (Exception ignored) {
        }
    }

    public void setMessageList(List<DBMessage> messageList) {
        try {
            mDaoSession.getDBMessageDao().insertOrReplaceInTx(messageList);
        } catch (Exception ignored) {
        }
    }

    public List<DBMessage> getMessageList() {
        try {
            return mDaoSession.getDBMessageDao().queryBuilder().orderDesc(DBMessageDao.Properties.PushTime).list();
        } catch (Exception ignored) {
            return null;
        }
    }

}
